package com.yan.mvc.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;


/**
 * 引入spring security
 */

@Configuration
@EnableWebSecurity
public class WebAppSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Bean
    public BCryptPasswordEncoder getPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder builder) throws Exception {

        // 让security临时使用内存来检查账号密码
        // builder.inMemoryAuthentication().withUser("tom").password("123123").roles("ADMIN");

        // 基于DB的认证
        builder.userDetailsService(userDetailsService)
                .passwordEncoder(getPasswordEncoder());

    }

    @Override
    protected void configure(HttpSecurity security) throws Exception {
        // String数组，列出需要放行的资源的路径
        String[] permitUrls = {"/index.jsp", "/bootstrap/**",
                "/crowd/**", "/css/**", "/fonts/**", "/img/**",
                "/jquery/**", "/layer/**", "/script/**", "/ztree/**", "/admin/login/page.html"};
        security
                .authorizeRequests()        // 表示对请求进行授权
                .antMatchers(permitUrls)    // 传入的ant风格的url
                .permitAll()                // 允许上面的所有请求，不需要认证

                .anyRequest()               // 设置其他未设置的全部请求
                .authenticated()            // 表示需要认证
                .and()
                .csrf()                     // 关闭csrf
                .disable()
                .formLogin()                // 开启表单登录功能
                .loginPage("/admin/to/login/page.html") // 指定登录页
                .loginProcessingUrl("/security/do/login.html") // 指定登录请求的表单
                .defaultSuccessUrl("/admin/to/main/page.html") // 指定登录成功后前往的地址
                .usernameParameter("loginAcct")
                .passwordParameter("userPswd")
                .and()
                .logout()                   // 对退出功能进行权限控制
                .logoutUrl("/security/do/logout.html")              // 指定退出登录地址
                .logoutSuccessUrl("/admin/to/login/page.html")       // 退出成功前往的地址
        ;
    }
}
